package org.example.admin.common.toolkit;

import java.security.SecureRandom;
import java.util.Random;

/**
 * 随机字符串生成器
 *
 * @author weibing
 * @since 2025/10/3 19:28
 */
public class RandomStringGenerator {

    // 字符池：0-9 + a-z + A-Z
    private static final String CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final int LENGTH = 6;
    private static final Random RANDOM = new SecureRandom();

    /**
     * 生成6位随机字符串（包含数字和字母）
     *
     * @return 随机字符串
     */
    public static String generate() {
        return generate(LENGTH);
    }

    /**
     * 生成指定长度的随机字符串（包含数字和字母）
     *
     * @param length 字符串长度
     * @return 随机字符串
     */
    public static String generate(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("长度必须大于0");
        }

        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            // 从字符池中随机选择一个字符
            int randomIndex = RANDOM.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(randomIndex));
        }
        return sb.toString();
    }

    // 测试方法
    public static void main(String[] args) {
        // 生成10个随机字符串示例
        for (int i = 0; i < 10; i++) {
            System.out.println("随机字符串 " + (i + 1) + ": " + generate());
        }
    }
}